package com.sry.blog.sys.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sry.blog.common.api.CommonResult;
import com.sry.blog.dto.ArticleDTO;
import com.sry.blog.sys.model.Article;
import com.sry.blog.sys.model.ArticleToTag;
import com.sry.blog.sys.model.Tag;
import com.sry.blog.sys.service.ArticleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * InnoDB free: 10240 kB; (`author`) REFER `blog/user`(`id`) ON UPDATE CASCADE 前端控制器
 * </p>
 *
 * @author SR_Y
 * @since 2022-01-05
 */
@RestController
@RequestMapping("/article")
@Slf4j
public class ArticleController {
    @Autowired
    private ArticleService articleService;

    @Autowired
    private TagController tagController;

    @Autowired
    private ArticleToTagController articleToTagController;


    public boolean create(Article article) {
        Date date = new Date();
        if (null == article.getId()) {
            article.setPublishTime(date);
            article.setReadCount(0);
            article.setIsdelete(0);
            article.setStatus(0);
        }
        article.setRecentEdit(date);
        return articleService.creatOrUpdate(article);

    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public boolean save(@RequestBody ArticleDTO articleDTO) {
        articleDTO.setTags(tagController.creates(articleDTO.getTags()));
        Date date = new Date();
        final Article article = Article.builder().title(articleDTO.getArticle().getTitle()).content(articleDTO.getArticle().getContent()).introduce(articleDTO.getArticle().getIntroduce()).author(articleDTO.getArticle().getAuthor()).build();
        if (create(articleDTO.getArticle())) {
            log.info("创建文章成功");
            Article article1 = articleService.getOne(article);
            Integer articleID = article1.getId();
            log.info(String.valueOf(articleDTO.getTags().size()));
            for (Tag tag : articleDTO.getTags()) {
                articleToTagController.create(ArticleToTag.builder().articleId(articleID).tagId(tag.getId()).build());
            }
            return true;
        } else {
            log.info("创建文章失败");
            return false;
        }

    }

    /**
     * 修改文章
     *
     * @param article
     * @return
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public boolean update(@RequestBody Article article) {
        Date date = new Date();
        article.setRecentEdit(date);
        return articleService.creatOrUpdate(article);
    }

    /**
     * 查询文章
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/get", method = RequestMethod.POST)
    @ResponseBody
    public Article getOne(@RequestBody Article article) {
        return articleService.getOne(article);
    }

    /**
     * 查询文章
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/getById", method = RequestMethod.GET)
    @ResponseBody
    public Article getOneById(@RequestParam("id") Integer id) {
        return articleService.getOneById(id);
    }

    /**
     * 查询所有文章
     *
     * @return
     */
    @RequestMapping(value = "/homePage", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<List<ArticleDTO>> gethomePage(@RequestParam(value = "tagId", defaultValue = "0") Integer tagId) {
        List<Article> articles = new ArrayList<>();
        if (tagId != 0) {
            List<ArticleToTag> articleToTags = articleToTagController.getArticles(tagId);
            for (ArticleToTag articleToTag : articleToTags) {
                articles.add(articleService.getOneById(articleToTag.getArticleId()));
            }
        } else {
            articles = articleService.list(Article.builder().build());
        }
        return getListCommonResult(articles);
    }

    @RequestMapping(value = "/search", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<List<ArticleDTO>> search(@RequestParam(value = "keyword", defaultValue = "") String keyword) {
        List<Article> articles = articleService.list(Article.builder().content(keyword).introduce(keyword).title(keyword).build());
        return getListCommonResult(articles);
    }

    private CommonResult<List<ArticleDTO>> getListCommonResult(List<Article> articles) {
        articles.removeIf(article -> article.getStatus() == 0);
        List<ArticleDTO> articleDTOS = new ArrayList<>();
        for (Article article : articles) {
            articleDTOS.add(ArticleDTO.builder().article(article).tags(articleToTagController.getTags(article.getId())).build());
        }
        return CommonResult.success(articleDTOS);
    }

    @RequestMapping(value = "/getList", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<Page<ArticleDTO>> getList(@RequestBody Article article,
                                                  @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                  @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {
        Page<ArticleDTO> articleDTOS = new Page<>(pageNum, pageSize);
        List<Article> list = articleService.list(article, pageNum, pageSize);
        List<ArticleDTO> articleDTOList = new ArrayList<>();
        for (Article a : list) {
            articleDTOList.add(ArticleDTO.builder().article(a).tags(articleToTagController.getTags(a.getId())).build());
        }
        articleDTOS.setRecords(articleDTOList);
        articleDTOS.setTotal(articleService.count(article));
        articleDTOS.setPages(articleDTOS.getTotal() / articleDTOS.getSize() + 1);
        return CommonResult.success(articleDTOS);
    }


//    @RequestMapping(value = "/uploadArticle", method = RequestMethod.POST)
//    public void uploadArticle(@RequestBody String markDown) {
//        //将字符串保存在指定位置的文件内
//        File file = FileUtil.writeUtf8String(markDown, "D:\\test.md");
//    }

    /**
     * @param id
     */
    @RequestMapping(value = "/readCountIncrease", method = RequestMethod.GET)
    @ResponseBody
    public void readCountIncrease(@RequestParam("id") Integer id) {
        articleService.readCountIncrease(id);
        log.info("阅读量增加成功");
    }

    @RequestMapping(value = "/getRecentArticle", method = RequestMethod.GET)
    @ResponseBody
    public List<Article> getRecentArticle() {
        return articleService.getRecentArticle();
    }

    //获取阅读量最高的5篇文章
    @RequestMapping(value = "/getHotArticle", method = RequestMethod.GET)
    @ResponseBody
    public List<Article> getHotArticle() {
        return articleService.getHotArticle();
    }


}

